package school.service;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import school.repository.CustomerDao;
import school.repository.ManagerDao;
import school.repository.StaffDao;

//import com.ibm.db2.jcc.a.SqlException;

public class SchoolUserDetailsService implements UserDetailsService {
	private CustomerDao customerDao;
	private StaffDao staffDao;
	private ManagerDao managerDao;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		try {
			UserDetails result = null;

			result = this.customerDao.getByUsername(username);

			if (result == null) {
				result = this.staffDao.getByUsername(username);
				if (result == null) {
					result = this.managerDao.getByUsername(username);
				}
			}

			if (result == null) {
				throw new UsernameNotFoundException("No such user");
			}

			return result;

		/*} catch (SqlException e) {
			System.out.println(e.getErrorCode() + ", " + e.getSQLState());
			throw new DataRetrievalFailureException("DB Error!", e);*/
		} catch (Exception e) {
			e.printStackTrace();
			throw new DataRetrievalFailureException("DB Error!", e);
		}
	}

	public CustomerDao getCustomerDao() {
		return customerDao;
	}

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	public StaffDao getStaffDao() {
		return staffDao;
	}

	public void setStaffDao(StaffDao staffDao) {
		this.staffDao = staffDao;
	}

	public ManagerDao getManagerDao() {
		return managerDao;
	}

	public void setManagerDao(ManagerDao managerDao) {
		this.managerDao = managerDao;
	}

}
